using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Add", "AxRows")]
    public class Add_AXRows : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Table;

        [System.Management.Automation.Parameter(Position = 1, Mandatory = true)]
        public System.Data.DataTable DataTable;

        protected override void ProcessRecord()
        {
            var ax = new AXBC.Axapta();
            ax.Logon(null, null, null, null);

            var dic = new Dictionary<string, object>(this.DataTable.Columns.Count);

            var cols = this.DataTable.Columns;


            foreach (System.Data.DataRow row in this.DataTable.Rows)
            {
                dic.Clear();

                using (var rec = ax.CreateAxaptaRecord(this.Table))
                {
                    for (int i = 0; i < cols.Count; i++)
                    {
                        var colname = cols[i].ColumnName;
                        var coltype = cols[i].DataType;
                        var colval = row.ItemArray[i];

                        if (colval is System.DBNull)
                        {
                        }
                        else
                        {
                            rec.set_Field(colname, colval);
                        }
                    }

                    rec.Insert();
                }

            }


            ax.Logoff();
        }
    }
}
